package com.maslyk.invitation.audit;

import java.util.Date;

import javax.persistence.EntityManager;

import com.maslyk.invitation.BeanService;
import com.maslyk.invitation.entitybean.Auditlog;
import com.maslyk.invitation.entitybean.abstrct.GenericEntity;
import com.maslyk.invitation.service.PersistenceService;
import com.maslyk.invitation.to.CurrentUserTO;

public class AuditLogUtil {
	
	public static void LogIt(OperationType action, Object entity, String changes) {
		
		if(!(entity instanceof GenericEntity))
			return;
		
		GenericEntity genericEntity = (GenericEntity) entity;
		
		EntityManager em = null;
		try {
			em = PersistenceService.getInstance().getEntityManager();
			CurrentUserTO currentUser = (CurrentUserTO) BeanService.getSessionScopeBean("currentUserTO");
			Auditlog auditRecord = new Auditlog(currentUser.getCurrentSalesman(),
												action.name(),
												changes,
												new Date(), 
												genericEntity.getId(), 
												entity.getClass().getAnnotation(ObjectName.class).label(), 
												genericEntity.getKey());
			em.getTransaction().begin();
			em.persist(auditRecord);
			em.getTransaction().commit();

		} finally {
			em.close();
		}
	}
}
